﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using iStudio.Format;
using iStudio.Structure.Control.Audio.Editor;
using iStudio.Structure.Engine;

namespace iStudio.Manager.Plugin
{
    public class PluginManager
    {
        public ReadOnlyCollection<Module> Modules
        {
            get;
            private set;
        }

        public ReadOnlyCollection<Format.Format> Formats
        {
            get;
            private set;
        }

        public ReadOnlyCollection<EditorTool> EditorTools
        {
            get;
            private set;
        }

        public ReadOnlyCollection<EditorRenderer> EditorRenderers
        {
            get;
            private set;
        }

        public ReadOnlyCollection<AudioEngine> AudioEngines
        {
            get;
            private set;
        }

        public List<FormatDescriptor> GetSupportedFileFormats(FormatSupport support)
        {
            List<FormatDescriptor> supported = new List<FormatDescriptor>();

            foreach (Format.Format format in Formats)
            {
                List<FormatDescriptor> supportedInFormat = format.GetSupportedFileFormats (support);

                supported.AddRange (supportedInFormat);
            }

            return supported;
        }

        public void LoadPlugins ()
        {
            Modules = new ReadOnlyCollection<Module> (new List<Module> (LoadPlugins<Module>(Environment.CurrentDirectory)));
            Formats = new ReadOnlyCollection<Format.Format>(new List<Format.Format>(LoadPlugins<Format.Format>(Environment.CurrentDirectory)));
            EditorTools = new ReadOnlyCollection<EditorTool>(new List<EditorTool>(LoadPlugins<EditorTool>(Environment.CurrentDirectory)));
            EditorRenderers = new ReadOnlyCollection<EditorRenderer> (new List<EditorRenderer>(LoadPlugins<EditorRenderer> (Environment.CurrentDirectory)));
            AudioEngines = new ReadOnlyCollection<AudioEngine> (new List<AudioEngine>(LoadPlugins<AudioEngine>(Environment.CurrentDirectory)));
        }

        protected IEnumerable<T> LoadPlugins<T>(string directory)
        {
            ComposablePartCatalog catalog = new DirectoryCatalog(directory);

            CompositionContainer container = new CompositionContainer(catalog);

            return container.GetExportedValues<T>();
        }
    }
}
